package com.shanshi.activity.addressSelector.adapters;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.shanshi.activity.EssayInfoActivity;
import com.shanshi.activity.R;
import com.shanshi.activity.response.ArticleContent;
import com.shanshi.activity.tool.OkHttpTool;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.List;

public class ArticleAdapter extends BaseAdapter{
	private List<ArticleContent.Data> list;
	private Context context;
	private LayoutInflater from;
	private ViewHolder holder=null;
    public ArticleAdapter(Context context,List<ArticleContent.Data> list){
    	from = LayoutInflater.from(context);
    	this.context=context;
    	this.list=list;
    }

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView==null) {
			convertView=from.inflate( R.layout.spread_message_itme, null);
			holder=new ViewHolder();
			holder.coverimage1=(ImageView) convertView.findViewById(R.id.coverimage1);
			holder.articleTitle=(TextView) convertView.findViewById(R.id.articleTitle);
			holder.articleSynopsis=(TextView) convertView.findViewById(R.id.articleSynopsis);
			holder.leaveWordNum=(TextView) convertView.findViewById(R.id.leaveWordNum);
			holder.praiseNum=(TextView) convertView.findViewById(R.id.praiseNum);
			holder.readTextBt=(Button) convertView.findViewById(R.id.readTextBt);
			holder.careImg=(ImageView) convertView.findViewById(R.id.careImg);
			holder.leaveWordImg=(ImageView) convertView.findViewById(R.id.leaveWordImg);
			holder.imageView1=(ImageView) convertView.findViewById(R.id.imageView1);
			convertView.setTag(holder);
		}else{
			holder=(ViewHolder) convertView.getTag();
		}
		Glide
		  .with(context)
		  .load(list.get(position).getImgurl()).centerCrop()
		  .into(holder.coverimage1);
		holder.articleTitle.setText(list.get(position).getTitle());
		holder.articleSynopsis.setText(list.get(position).getIntroduction());
		holder.leaveWordNum.setText(list.get(position).getCommentcount()+"");
		holder.praiseNum.setText(list.get(position).getPraisecount()+"");
		setPraiseAndCare(0, list.get(position).getPraise());
		setPraiseAndCare(1, list.get(position).getAttention());
		Log.e("===dadad", list.get(position).getPraise()+"");
		Log.e("===dadad", list.get(position).getAttention()+"");
		holder.careImg.setOnClickListener(new OnClickListener() {    //收藏
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//创建OkHttpClient对象
				OkHttpClient client = new OkHttpClient();
				//通过FormEncodingBuilder对象添加多个请求参数键值对
				FormEncodingBuilder builder = new FormEncodingBuilder();
				Request request;
				if (!list.get(position).getAttention()) {
					builder.add("method", "post");
					//通过FormEncodingBuilder对象构造Post请求体
					RequestBody body = builder.build();
					//通过请求地址和请求体构造Post请求对象Request
					request = new Request.Builder().url(OkHttpTool.BASE_URL+"users/"+4+"/"+"articles/"+
					list.get(position).getId()
							+"/collection").post(body).build();
				}else {
					builder.add("method", "delete");
					//通过FormEncodingBuilder对象构造Post请求体
					RequestBody body = builder.build();
					//通过请求地址和请求体构造Post请求对象Request
					request = new Request.Builder().url(OkHttpTool.BASE_URL+"users/"+4+"/"+"articles/"+
					list.get(position).getId()
							+"/collection").delete(body).build();
				}
				client.newCall(request).enqueue(new Callback() {
					
					@Override
					public void onResponse(Response arg0) throws IOException {
						// TODO Auto-generated method stub
						Log.e("====ads", arg0.body().string().toString());
						list.get(position).setAttention(!list.get(position).getAttention());
						Log.e("====ads", list.get(position).getPraise()+"");
						handler.sendEmptyMessage(1);
					}
					
					@Override
					public void onFailure(Request arg0, IOException arg1) {
						// TODO Auto-generated method stub
						
					}
				});
				
				
			}
		});
		holder.leaveWordImg.setOnClickListener(new OnClickListener() {   //评论
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(position);
				
			}
		});
		holder.imageView1.setTag(position);
		holder.imageView1.setOnClickListener(new OnClickListener() {  //点赞
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//创建OkHttpClient对象
				OkHttpClient client = new OkHttpClient();
				//通过FormEncodingBuilder对象添加多个请求参数键值对
				FormEncodingBuilder builder = new FormEncodingBuilder();
				Request request;
				if (!list.get(position).getPraise()) {
					builder.add("method", "post");
					//通过FormEncodingBuilder对象构造Post请求体
					RequestBody body = builder.build();
					//通过请求地址和请求体构造Post请求对象Request
					request = new Request.Builder().url(OkHttpTool.BASE_URL+"users/"+4+"/"+"articles/"+
					list.get(position).getId()
							+"/praise").post(body).build();
				}else {
					builder.add("method", "delete");
					//通过FormEncodingBuilder对象构造Post请求体
					RequestBody body = builder.build();
					//通过请求地址和请求体构造Post请求对象Request
					request = new Request.Builder().url(OkHttpTool.BASE_URL+"users/"+4+"/"+"articles/"+
					list.get(position).getId()
							+"/praise").delete(body).build();
				}
				client.newCall(request).enqueue(new Callback() {
					
					@Override
					public void onResponse(Response arg0) throws IOException {
						// TODO Auto-generated method stub
						Log.e("====ads", arg0.body().string().toString());
						if (!list.get(position).getPraise()) {
							list.get(position).setPraisecount(list.get(position).getPraisecount()+1);
						}else {
							list.get(position).setPraisecount(list.get(position).getPraisecount()-1);
						}
						list.get(position).setPraise(!list.get(position).getPraise());
						Log.e("====ads", list.get(position).getPraise()+"");
						handler.sendEmptyMessage(1);
					}
					
					@Override
					public void onFailure(Request arg0, IOException arg1) {
						// TODO Auto-generated method stub
						
					}
				});
			}				
		});
		holder.readTextBt.setOnClickListener(new OnClickListener() {    //阅读全文

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(context,EssayInfoActivity.class);
				intent.putExtra("articleId",list.get(position).getId());
				context.startActivity(intent);
			}
		});
		return convertView;
	}
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				Log.e("====", "dsada");
				notifyDataSetChanged();
				break;

			default:
				break;
			}	
		};
	};
	
    private static class ViewHolder{
    	ImageView coverimage1;   //图片
    	TextView articleTitle;  //文章标题
    	TextView articleSynopsis;   //文章内容
    	TextView leaveWordNum;   //评论数
    	Button readTextBt;   //阅读全文按钮
    	TextView praiseNum;  //赞数
    	ImageView leaveWordImg;   //评论图标跳转
    	ImageView imageView1;     //点赞与否
    	ImageView careImg;   //收藏
    }
    
    //根据点赞情况与关注情况判断显示的对应的图片
    private void setPraiseAndCare(int i,boolean is){
    	if (i==0) {   //点赞
    		if (is) {
				holder.imageView1.setImageResource(R.drawable.praise_in);
			}else {
				holder.imageView1.setImageResource(R.drawable.praise_no);
			}
		}else {    //关注
			if (is) {
				holder.careImg.setImageResource(R.drawable.heart_1);
			}else {
				holder.careImg.setImageResource(R.drawable.heart_0);
			}
		}
    }
    
    //彈窗
    private Dialog dialog;
    private EditText editText;
    private void showDialog(final int postion){
    	 dialog = new Dialog(context, R.style.dialog);
         LayoutInflater inflater = LayoutInflater.from(context);
         final View view = inflater.inflate(R.layout.dialog_leave_word, null);
         editText=(EditText) view.findViewById(R.id.edit);
         RelativeLayout rey=(RelativeLayout) view.findViewById(R.id.reylay);
         ImageView close=(ImageView) view.findViewById(R.id.close);
         Button submit=(Button) view.findViewById(R.id.submit);
         close.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
         rey.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				InputMethodManager imm = ( InputMethodManager ) editText.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );     
				imm.showSoftInput(editText,InputMethodManager.SHOW_FORCED);
			}
		});
         submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (editText.getText().length()>0) {
				//创建OkHttpClient对象
				OkHttpClient client = new OkHttpClient();
				Request request;
				RequestBody body =RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
						"{\"content\":\""+editText.getText().toString()+"\"}");
					//通过请求地址和请求体构造Post请求对象Request
					request = new Request.Builder().url(OkHttpTool.BASE_URL+"users/"+4+"/"+"articles/"+
					list.get(postion).getId()
							+"/comment").post(body).build();
				client.newCall(request).enqueue(new Callback() {
					
					@Override
					public void onResponse(Response arg0) throws IOException {
						// TODO Auto-generated method stub
						Log.e("====ads", arg0.body().string().toString());
						list.get(postion).setCommentcount(list.get(postion).getCommentcount()+1);
						handler.sendEmptyMessage(1);
						if (dialog!=null) {
							dialog.dismiss(); 
						}
						InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		            	imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘 
					}
					
					@Override
					public void onFailure(Request arg0, IOException arg1) {
						// TODO Auto-generated method stub
						
					}
				});
			}else {
				Toast.makeText(context, "评论不能为空哦~", Toast.LENGTH_SHORT).show();
			}
			}
		});
         
         
         dialog.show();
         dialog.getWindow().setContentView(view);
         dialog.setCanceledOnTouchOutside(true);// 设置点击屏幕Dialog消失
         WindowManager windowManager = ((Activity) context).getWindowManager();
         Display display = windowManager.getDefaultDisplay();
         WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
         lp.height = (int) (display.getHeight()*1/3); //设置宽度
         dialog.getWindow().setAttributes(lp);
    }
    
}
